package com.wwdx.controller.rest;

import com.google.common.collect.Maps;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.WwdxVipProductModel;
import com.wwdx.model.dto.BaseActivityDTO;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * @author liguoliang
 * @date 2017-11-16 13:29
 */
@RestController
@RequestMapping("task")
@ApiIgnore
public class RestTaskController extends BaseController{
    /**
     * 每天早上8点发-听书
     */
    @Scheduled(cron = "0 0 20 * * ?")
    public void sendMessage(){
        logger.info("20点00分执行");
        //活动提醒
        taskExecutor.execute(()-> {
            try {
                taskService.sendMessage();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    /**
     * 每天凌晨1点执行
     */
    @RequestMapping("/statistics/generated")
    public void generated(){
        //赠一得一按渠道统计
        taskExecutor.execute(()-> taskService.giveonechannel());
        //赠一得一按书籍统计
        taskExecutor.execute(()-> taskService.giveonebook());
        //赠一得一按用户统计
        taskExecutor.execute(()-> taskService.giveoneuser());
        //早读听书打卡统计
        taskExecutor.execute(()-> taskService.cardReading());
        //首页订阅统计
        taskExecutor.execute(()-> taskService.homeSubscribe());
        //页面统计
        taskExecutor.execute(()-> taskService.executePageStatistics());
        //收入统计导出
        taskExecutor.execute(()-> taskService.statisticsIncomeExcute());
        //商户分销统计
        taskExecutor.execute(()-> taskService.executeMerchantProductStatistics());
        //定时清理过期会员
        taskExecutor.execute(()-> taskService.cleanExpireVip());
    }

    /**
     * 每天凌晨3点执行
     */
    @RequestMapping("/statistics/export")
    public void export(){
        //订单表导出
        taskExecutor.execute(()-> taskService.exportWwdxOrder());
        //收入统计导出
        taskExecutor.execute(()-> taskService.exportIncome());
        //同步|更新微信用户信息
        taskExecutor.execute(()-> taskService.synUserInfo(null));
        //每天上新书籍
        Set<Object> rangeByScore = zSetOperations.range(ConstantHolder.BOOK_ONLINE_ZSET, 0,-1);
        if (!CollectionUtils.isEmpty(rangeByScore)){
            Object obj = rangeByScore.iterator().next();
            Long bookid = Long.valueOf(obj.toString());
            WwdxBookModel wwdxBookModel = wwdxBookService.getByBookId(bookid);
            wwdxBookModel.setIshost(1);wwdxBookModel.setStatus(0);wwdxBookModel.setGmtModified(new Date());
            wwdxBookModel.setSort(zSetOperations.score(ConstantHolder.BOOK_ONLINE_ZSET,obj).intValue());
            wwdxBookService.update(wwdxBookModel);
        }
    }

    /**
     * 每周日清除赠一得一数据
     */
    @RequestMapping("/clean/giveone")
    public void cleangiveone(){
        String phaseListKey = ConstantHolder.GIVEONE_PHASE_LIST;
        Object object = listOperations.index(phaseListKey, 0);
        if (object != null){
            BaseActivityDTO.GiveOneDTO giveOneDTO = (BaseActivityDTO.GiveOneDTO) valueOperations.get(object.toString());
            String phase = giveOneDTO.getPhase();
            listOperations.leftPop(phaseListKey);
            redisTemplate.delete(String.format(ConstantHolder.GIVEONE_BOOK_LIST, phase));
            redisTemplate.delete(String.format(ConstantHolder.GIVEONE_PHASE_OBJ, phase));
        }
    }

    /**
     * 每天7点执行
     */
//    @RequestMapping("/notice")
//    public void notice(){
//        Set<Object> rangeByScore = zSetOperations.range(ConstantHolder.BOOK_ONLINE_ZSET, 0,-1);
//        if (!CollectionUtils.isEmpty(rangeByScore)){
//            Object obj = rangeByScore.iterator().next();
//            Long bookid = Long.valueOf(obj.toString());
//            int phase = zSetOperations.score(ConstantHolder.BOOK_ONLINE_ZSET, obj).intValue();
//            //vip上新通知
//            //taskExecutor.execute(()-> templateMsgTaskService.sendVipPlanTemplate(bookid,phase));
//            //首页订阅用户
//            taskExecutor.execute(()-> templateMsgTaskService.sendSubscribeTemplate(bookid,phase));
//            //删除书籍online
//            zSetOperations.remove(ConstantHolder.BOOK_ONLINE_ZSET,obj);
//        }
//        //vip过期通知
//        taskExecutor.execute(()-> templateMsgTaskService.sendVipExpiresTemplate());
//    }

    /**
     * 活动提醒 - 所有订阅听书用户
     */
    @Scheduled(cron = "0 0 18 15 11 ?")
    public void activeNotice(){
        logger.info("每天6点55分执行");
        //活动提醒
        taskExecutor.execute(()-> templateMsgTaskService.sendActiveNoticeTemplate());
    }

    /**
     * 活动提醒 - 所有关注公众号用户
     */
    @Scheduled(cron = "0 0 17 20 11 ?")
    public void activeNotice2(){
        logger.info("17点00分执行");
        //活动提醒
        taskExecutor.execute(()-> templateMsgTaskService.sendActiveNoticeTemplate2());
    }

    /**
     * vip活动到期-还原数据
     */
    @Scheduled(cron = "0 0 17 20 11 ?")
    public void activeExpire(){
        logger.info("活动到期，更新原数据");
        //活动提醒
        taskExecutor.execute(()-> {
            WwdxVipProductModel wwdxVipProductModel = wwdxVipProductService.getByProductId(10003L);
            if (wwdxVipProductModel!=null){
                //原价 现价
                wwdxVipProductModel.setOriginal_price(new BigDecimal(45));
                wwdxVipProductModel.setPrice(new BigDecimal(45));
                wwdxVipProductService.update(wwdxVipProductModel);
            }
        });
    }

    /**
     * 获取上新书籍
     */
    @RequestMapping("/notice/book")
    public ResultBean noticeBookId(){
        Set<Object> rangeByScore = zSetOperations.range(ConstantHolder.BOOK_ONLINE_ZSET, 0,-1);
        if (!CollectionUtils.isEmpty(rangeByScore)){
            Object obj = rangeByScore.iterator().next();
            Long bookid = Long.valueOf(obj.toString());
            int phase = zSetOperations.score(ConstantHolder.BOOK_ONLINE_ZSET, obj).intValue();
            HashMap<String, Object> map = Maps.newHashMapWithExpectedSize(2);
            map.put("bookid",bookid);
            map.put("phase",phase);
            return renderSuccess(map);
        }
        return renderError("book missing");
    }
}